
#include "Texture.h"
#include "Engine.h"

Texture *Texture::current = 0;
TextureManager *tManager = new TextureManager();

//
// Constructor
//

Texture::Texture(TCHAR *_fileName) 
{
	wcsncpy(fileName, _fileName, 60);
	if(FAILED(D3DXCreateTextureFromFile(engine.direct3DRenderer, fileName, &texture)))
	{
		texture = 0;

		TCHAR str[70];
		StringCchPrintf(str, 70, L"Could not find file: %s", fileName);
		MessageBox(NULL, str, L"Target Engine", MB_OK);
	}
}

Texture::Texture(TCHAR *_fileName, Color alpha) 
{
	wcsncpy(fileName, _fileName, 60);
	if(FAILED(D3DXCreateTextureFromFileEx(engine.direct3DRenderer, 
																				fileName, 
																				D3DX_DEFAULT,
																				D3DX_DEFAULT,
																				D3DX_DEFAULT,
																				D3DUSAGE_RENDERTARGET,
																				D3DFMT_FROM_FILE,
																				D3DPOOL_DEFAULT,
																				D3DX_DEFAULT,
																				D3DX_DEFAULT,
																				alpha.color,
																				NULL,
																				NULL,
																				&texture)))
	{
		texture = 0;

		TCHAR str[70];
		StringCchPrintf(str, 70, L"Could not find file: %s", fileName);
		MessageBox(NULL, str, L"Target Engine", MB_OK);
	}
}

//
// LoadTexture
//

void Texture::Load() 
{
	// Don't reload the current texture
	if(this == current) return;

	engine.direct3DRenderer->SetTexture(0, texture);

  engine.direct3DRenderer->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
  engine.direct3DRenderer->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
  engine.direct3DRenderer->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);

	current = this;
}

//
// Clears the loaded texture
//

void Texture::Clear() 
{
	if(current)
	{
		engine.direct3DRenderer->SetTexture(0, NULL);
		current = NULL;
	}
}

//
// Release
//

void Texture::Release() 
{
	if(texture)
		texture->Release();
}

//
// Create Texture
//

Texture *TextureManager::CreateTexture(TCHAR *fileName)
{
	for(uint i = 0; i < textures.size(); i++)
		if(wcscmp(fileName, textures[i]->fileName) == 0)
			return textures[i];

	Texture *t = new Texture(fileName);
	textures.push_back(t);
	return textures[textures.size()-1];
}

Texture *TextureManager::CreateTexture(TCHAR *fileName, Color alpha)
{
	for(uint i = 0; i < textures.size(); i++)
		if(wcscmp(fileName, textures[i]->fileName) == 0)
			return textures[i];

	Texture *t = new Texture(fileName, alpha);
	textures.push_back(t);
	return textures[textures.size()-1];
}

//
// Release
//

void TextureManager::Release()
{
	for(uint i = 0; i < textures.size(); i++)
		textures[i]->Release();
}
